package com.penghaisoft.microwms.product.service.impl;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.ProBarcode;
import com.penghaisoft.microwms.common.dto.ProBarcodeDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.MsbarCode;
import com.penghaisoft.microwms.common.wms.model.ProCheckIn;
import com.penghaisoft.microwms.common.wms.model.ProOrderInSn;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.product.dao.*;
import com.penghaisoft.microwms.product.service.IProBarcodeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 业务逻辑实现类
 * </p>
 *
 * @author
 * @createDate
 **/
@Service("proBarcodeService")
public class ProBarcodeServiceImpl extends BaseService implements IProBarcodeService {
    @Resource
    private ProBarcodeMapper proBarcodeMapper;
    @Resource
    private ProStorageSnMapper proStorageSnMapper;
    @Resource
    private ProOrderInSnMapper proOrderInSnMapper;
    @Resource
    private ProCheckInMapper proCheckInMapper;

    @Resource
    private MsbarCodeMapper msbarCodeMapper;

    /**
     * 新增记录
     *
     * @param
     * @return
     */
    @Override
    public Resp create(ProBarcode proBarcode) {
        proBarcodeMapper.create(proBarcode);
        return success();
    }

    @Override
    public Resp codeCreate(ProCheckIn proCheckIn) {

        List<ProBarcode> proBarcodes = new ArrayList<>();
        List<String> barcodes = new ArrayList<>();
        List<String> codes = new ArrayList<>();
        String barcode = "";

        //根据生产时间查询当前条码最大值，获取大卷筒数值，新条码以最大值+1为起始值
        String bigNum = proBarcodeMapper.getBigNum().substring(7,9);
        Integer startNum = Integer.valueOf(bigNum);

        //条码拼接第一部分：当前时间
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        String code1 = sdf.format(now);
        String code1 = sdf.format(proCheckIn.getGmtProduct());
        barcode = barcode + code1.substring(2);
        //条码拼接第二部分：生产班组
        int code2 = Integer.parseInt(proCheckIn.getProductionTeam());
        barcode = barcode + code2;
        //条码拼接第三部分：大卷筒号
        for (int i=1;i<=proCheckIn.getBigNumber();i++){
            String code3 = "";
            int j = i+startNum;
            if (j<10){
                code3 = "0" + j;
            }else {
                code3 = code3 + j;
            }
            String bar = barcode + code3;
            barcodes.add(bar);
        }
        //条码拼接第四部分:复卷班组
        for (int i = 0;i<barcodes.size();i++){
            String code4 = "";
            code4 = code4 +  barcodes.get(i) + Integer.parseInt(proCheckIn.getRewindingTeam());
            codes.add(code4);

        }
        barcodes.clear();
        //条码拼接第五部分：复卷个数序号
        for (int i=0;i<codes.size();i++){
            for (int j=1;j<=proCheckIn.getRewindingNumber();j++){
                String code5= "";
                code5 = code5 + codes.get(i) + j;
                barcodes.add(code5);
            }
        }
        codes.clear();
        //条码拼接第六部分：复卷次数序号
        for (int i=0;i<barcodes.size();i++){
            for (int j=1;j<=proCheckIn.getRewindingCount();j++){
                String code6 = "";
                code6 = code6 + barcodes.get(i) + j;
                codes.add(code6);
            }
        }

        for (int i=0;i<codes.size();i++){
            ProBarcode proBarcode = new ProBarcode();
            proBarcode.setBarcode(codes.get(i));
            proBarcode.setModel(proCheckIn.getModel());
            proBarcode.setProductName(proCheckIn.getProductName());
            proBarcode.setDensity(proCheckIn.getDensity());
            proBarcode.setSpec(proCheckIn.getSpec());
            proBarcode.setMachineNumber(Integer.valueOf(proCheckIn.getMachineNumber()));
            proBarcode.setGrade(proCheckIn.getGrade());
            proBarcode.setLevel(proCheckIn.getLevel());
            proBarcode.setType(proCheckIn.getType());
            proBarcode.setUnit(proCheckIn.getUserDefined1());
            proBarcode.setUserDefined2(proCheckIn.getCheckInNo());
            proBarcode.setCreateBy(proCheckIn.getLoginName());
            proBarcode.setGmtCreate(new Date());
            proBarcode.setGmtModified(new Date());
            proBarcode.setUnit(proCheckIn.getUnit());
            proBarcode.setStatus("0");
            proBarcode.setUserDefined1("0");
            proBarcode.setActiveFlag("1");
            proBarcodeMapper.create(proBarcode);

            // 往条码打印接口表中插入数据
            MsbarCode msbarCode = new MsbarCode();
            msbarCode.setBarCode(proBarcode.getBarcode());
            msbarCode.setBarCodeSize(Constant.CODE_ONE);
            msbarCode.setModel(proBarcode.getModel());
            msbarCode.setProductName(proBarcode.getProductName());
            msbarCode.setDensity(proBarcode.getDensity());
            msbarCode.setSpec(proBarcode.getSpec());
            msbarCode.setGrade(proBarcode.getGrade());
            msbarCode.setUpdateDate(new Date());
            msbarCode.setIsPrint(new Boolean("0"));
            // 批次号
            msbarCode.setBatchCode(proCheckIn.getCheckInNo());
            msbarCodeMapper.create(msbarCode);
        }
        ProCheckIn checkIn = new ProCheckIn();
        checkIn.setCheckInId(proCheckIn.getCheckInId());
        checkIn.setAmount(codes.size());
        checkIn.setUserDefined2("1");
        proCheckInMapper.updateBySelect(checkIn);

        return success();
    }

    /**
     * 删除记录（逻辑删除）
     *
     * @param
     * @return
     */
    @Override
    public Resp delete(ProBarcode proBarcode) {
        proBarcodeMapper.delete(proBarcode);
        return success();
    }

    /**
     * 查询列表
     *
     * @param
     * @param
     * @return
     */
    @Override
    public Pager<ProBarcode> findListByCondition(int page, int rows, ProBarcode condition) {
        Pager<ProBarcode> pager = new Pager<>();
        pager.setPage(page);
        pager.setRows(rows);
        condition.preQuery();
        List<ProBarcode> records = proBarcodeMapper.queryList(pager, condition);
        long size = proBarcodeMapper.queryCount(condition);
        pager.setRecords(records);
        pager.setTotalCount(size);
        return pager;
    }

    /**
     * 查询单条
     *
     * @param id
     * @return
     */
    @Override
    public ProBarcode findById(String id) {
        return proBarcodeMapper.queryById(id);
    }

    /**
     * 修改记录
     *
     * @param
     * @return
     */
    @Override
    public Resp update(ProBarcode proBarcode) {
        proBarcodeMapper.updateBySelect(proBarcode);
        return success();
    }

    /**
     * @param proBarcodeDto
     * @return
     * @Title downlineScanBarcode
     * @Description 下线扫码入库
     * @author luoteng
     * @date 2018年6月7日:上午10:08:12
     */
    @Transactional
    @Override
    public TransResult downlineScanBarcode(ProBarcodeDto proBarcodeDto) {
        TransResult result = new TransResult();
        result.setCode(Constant.SUCCESS);

        Date now = new Date();


        ProBarcode proBarcode = new ProBarcode();
        proBarcode.setBarcode(proBarcodeDto.getBarcode());

        proBarcode.setActiveFlag("1");

        List<ProBarcode> proBarcodeList = proBarcodeMapper.queryByAny(proBarcode);
        if (proBarcodeList == null || proBarcodeList.isEmpty()) {
            result.setCode(Constant.FAIL);
            result.setMsg("该条码未下线。");
            return result;
        } else if (proBarcodeList.size() > 1) {
            result.setCode(Constant.FAIL);
            result.setMsg("该下线条码重复。");
            return result;
        } else {
            ProBarcode tmp = proBarcodeList.get(0);
//	        	入库状态 0：创建 1：已下线入库
            if (tmp.getUserDefined1() != null && tmp.getUserDefined1().equals("1")) {
                result.setCode(Constant.FAIL);
                result.setMsg("该条码已经下线入库。");
                return result;
            }

//	        	入库状态 0：创建 1：已下线入库
            tmp.setUserDefined1("1");
//            tmp.setWlCode(Constant.DEFAULT_WL_CODE);
            tmp.setWlCode(proBarcodeDto.getWlCode());
            tmp.setGmtCreate(now);
            tmp.setLastModifiedBy(proBarcodeDto.getLoginName());
            tmp.setGmtModified(now);
            tmp.setUserDefined1("1");

            proBarcodeMapper.updateBySelect(tmp);

            ProStorageSn proStorageSn = new ProStorageSn();
            proStorageSn.setBarcode(tmp.getBarcode());
            proStorageSn.setUnit(tmp.getUnit());
            proStorageSn.setModel(tmp.getModel());
            proStorageSn.setType(tmp.getType());
            proStorageSn.setProManuDate(now);
            proStorageSn.setProPlanDate(tmp.getGmtCreate());
            proStorageSn.setWlCode(proBarcodeDto.getWlCode());
//	        	0：可用 1：冻结 2：已出库 3：抽检冻结
            proStorageSn.setBarcodeStatus("0");
            proStorageSn.setCreateBy(proBarcodeDto.getLoginName());
            proStorageSn.setGmtCreate(now);
            proStorageSn.setActiveFlag("1");
            proStorageSn.setWeight(new BigDecimal(proBarcodeDto.getWeight()));
            proStorageSn.setProductName(tmp.getProductName());
            proStorageSn.setDensity(tmp.getDensity());
            proStorageSn.setSpec(tmp.getSpec());
            proStorageSn.setMachineNumber(tmp.getMachineNumber());
            proStorageSn.setGrade(tmp.getGrade());
            proStorageSn.setLevel(tmp.getLevel());
            proStorageSn.setBarcodeStatus("0");


            proStorageSnMapper.create(proStorageSn);

            ProOrderInSn proOrderInSn = new ProOrderInSn();
            proOrderInSn.setBarcode(tmp.getBarcode());
            proOrderInSn.setUnit(tmp.getUnit());
            proOrderInSn.setModel(tmp.getModel());
            proOrderInSn.setType(tmp.getType());
            proOrderInSn.setProPlanDate(tmp.getGmtCreate());
            proOrderInSn.setWlCode(proBarcodeDto.getWlCode());
//	        	0：可用 1：冻结 2：已出库 3：抽检冻结
            proOrderInSn.setBarcodeStatus("0");
            proOrderInSn.setCreateBy(proBarcodeDto.getLoginName());
            proOrderInSn.setGmtCreate(now);
            proOrderInSn.setActiveFlag("1");
            proOrderInSn.setProductName(tmp.getProductName());
            proOrderInSn.setDensity(tmp.getDensity());
            proOrderInSn.setSpec(tmp.getSpec());
            proOrderInSn.setMachineNumber(tmp.getMachineNumber());
            proOrderInSn.setGrade(tmp.getGrade());
            proOrderInSn.setLevel(tmp.getLevel());
            proOrderInSn.setBarcodeStatus("0");
            proOrderInSn.setProInDate(now);
            proOrderInSn.setBarcodeStatus("1");

            proOrderInSnMapper.create(proOrderInSn);


            ProCheckIn proCheckIn = new ProCheckIn();
            proCheckIn.setInAmount(1);
            proCheckIn.setCheckInNo(tmp.getUserDefined2());
            proCheckInMapper.updateInAmount(proCheckIn);
            List<ProBarcode> rtnList = new ArrayList<ProBarcode>();
            rtnList.add(tmp);
            result.setList(rtnList);
        }

        return result;
    }

    @Override
    public TransResult downlineDelBarcode(ProBarcodeDto proBarcodeDto) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public List<ProBarcode> queryList(ProBarcode proBarcode) {
		return proBarcodeMapper.queryList(null, proBarcode);
	}


}
